use anyhow::Result;
use db::Db;
use matrix_sdk::{
    room::Room,
    ruma::events::room::message::{
        OriginalSyncRoomMessageEvent, Relation, RoomMessageEventContent,
    },
    Client,
};

pub async fn show_alternative_url(
    ev: OriginalSyncRoomMessageEvent,
    _text: String,
    room: Room,
    _client: Client,
    db: Db,
) -> Result<()> {
    let relation = ev.content.relates_to.unwrap();
    if let Relation::Reply { in_reply_to } = relation {
        let event_id = in_reply_to.event_id.to_string();
        if let Some(userpost_id) = db.get_userpost_id(event_id).await? {
            let alternative_url = db.get_alternative_url(userpost_id).await?;
            if let Some(alternative_url) = alternative_url {
                // (row.get(0), row.get(1))
                let content = RoomMessageEventContent::text_markdown(format!(
                    "alternative url: {}",
                    alternative_url
                ));
                let response = room.send(content).await.unwrap();
                let event_id = response.event_id.to_string();
                db.create_message_event(userpost_id, event_id)
                    .await
                    .unwrap();
            }
        }
        log::info!("toggled show_alternative_url on post");
        // }
    }
    Ok(())
}
